package com.xbts.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbts.common.exception.ServiceException;
import com.xbts.common.utils.SecurityUtils;
import com.xbts.common.utils.StringUtils;
import com.xbts.system.domain.CnHwyTemplate;
import com.xbts.system.domain.dto.CnHwyTemplateTopDTO;
import com.xbts.system.mapper.CnHwyTemplateMapper;
import com.xbts.system.service.ICnHwyTemplateService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author : llk
 * @Date: 2024/4/10 10:55
 */
@Service
public class CnHwyTemplateServiceImpl extends ServiceImpl<CnHwyTemplateMapper, CnHwyTemplate> implements ICnHwyTemplateService {

    @Override
    public List<CnHwyTemplate> listData(String name) {
        LambdaQueryWrapper<CnHwyTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), CnHwyTemplate::getName, name);
        queryWrapper.orderByDesc(CnHwyTemplate::getIsTop);
        queryWrapper.orderByDesc(CnHwyTemplate::getCreateTime);
        return list(queryWrapper);
    }

    @Override
    public Boolean insertCnHwyTemplate(CnHwyTemplate cnHwyTemplate) {
        cnHwyTemplate.setCreateBy(SecurityUtils.getUsername());
        return save(cnHwyTemplate);
    }

    @Override
    public Boolean updateCnHwyTemplate(CnHwyTemplate cnHwyTemplate) {
        cnHwyTemplate.setUpdateBy(SecurityUtils.getUsername());
        cnHwyTemplate.setUpdateTime(new Date());
        return updateById(cnHwyTemplate);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchDeleteContentById(List<Long> ids) {
        return removeBatchByIds(ids);
    }

    @Override
    public Boolean top(CnHwyTemplateTopDTO topDTO) {
        CnHwyTemplate hwyTemplate = new CnHwyTemplate();
        hwyTemplate.setId(topDTO.getId());
        hwyTemplate.setIsTop(topDTO.getIsTop());

        if (topDTO.getIsTop() && checkIsTopNumber()) {
            throw new ServiceException("最多只能置顶2条数据，请先取消置顶再进行置顶操作");
        }
        return updateById(hwyTemplate);
    }

    /**
     * 判断置顶数据条数
     * @return
     */
    private Boolean checkIsTopNumber(){
        return lambdaQuery().eq(CnHwyTemplate::getIsTop,true).count() >= 2;
    }
}
